<template>
    <div>
        <el-card>
            <template #header>
                <el-button icon="Plus" @click="handleAdd" v-has="'btn.addTaste'">添加口味</el-button>
            </template>
            <el-table :data="records" style="width: 100%;" v-loading="loading" border>
                <el-table-column type="index" label="序号" width="80" align="center" />
                <el-table-column prop="name" label="口味类别" min-width="100" align="center" />
                <el-table-column label="操作" min-width="320" align="center">
                    <template #default="{ row }">
                        <el-button icon="Edit" @click="handleEdit(row)" v-has="'btn.editTaste'">编辑</el-button>
                        <el-button type="danger" icon="Delete" @click="handleDelete(row)"
                            v-has="'btn.deleteTaste'">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <el-dialog :title="isEdit ? '编辑口味' : '添加商口味'" v-model="dialogVisible" :close-on-click-modal="false">
            <AddOrEditTaste v-if="dialogVisible" :is-edit="isEdit" :id="id" @success="onSuccess"></AddOrEditTaste>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="Taste">
import { onMounted, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import AddOrEditTaste from './components/AddOrEditTaste.vue';
import { list, tasteRemove, } from '@/api/wx/taste';
import type { TasteType } from '@/api/wx/taste/types';

// ---------- 查询 ----------
const loading = ref(false)
let records = ref<TasteType[]>([])

onMounted(() => {
    submitForm()
})

const submitForm = async () => {
    loading.value = true
    const data = await list();
    if (data.code === 200) {
        records.value = data.data
    }
    loading.value = false
}

// ---------- 添加/编辑/删除 ----------
const isEdit = ref(false)
const dialogVisible = ref(false)
const id = ref()

const handleAdd = () => {
    dialogVisible.value = true
    isEdit.value = false
}
const handleEdit = (row: TasteType) => {
    dialogVisible.value = true
    isEdit.value = true
    id.value = row.id
}
const handleDelete = async (row: TasteType) => {
    ElMessageBox.confirm(`确认删除口味【${row.name}】吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        const data = await tasteRemove(row.id as number)
        if (data.code === 200) {
            ElMessage.success('删除成功');
            submitForm();
        } else {
            ElMessage.error('删除失败');
        }
    });
}
const onSuccess = () => {
    dialogVisible.value = false
    submitForm()
}
</script>

<style scoped lang="scss"></style>